package cn.bellychang.abstractfactory.demo03;

/**
 * 用反射去除switch或if 解除分支判断带来的耦合
 * @author ChangLiang
 * @date 2020/1/16
 */
public class DataAccess {

    private String datasource;

    public DataAccess(String datasource) {
        this.datasource = datasource;
    }

    public IUser getUser() {

        Object o = reflectObject("." + datasource + "User");

        return o == null ? null : (IUser) o;
    }

    public IDepartment getDepartment() {
        Object o = reflectObject("." + datasource + "Department");
        return o == null ? null : (IDepartment) o;
    }

    private Object reflectObject(String className) {
        // 根据字符串来构造对象
        try {
            Class<?> aClass = Class.forName(this.getClass().getPackage().getName() + className);
            return aClass.newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }
}
